/**
 * Created by Administrator on 2017/1/13.
 */

var GlobalConfig = require('../../../config/config.json');
var defaultGlobal = require('../../../config/defaultGlobal.json');

function GlobalManager() {
    this.config = {};

    this.usedRoomIds = {          //已经使用的房间号
        _id: "usedRoomIds",
        ids:{}
    }

    this.matchSN = {
        _id: "matchSN",
        value: {}
    };
}

GlobalManager.prototype = {

    /**
     * 初始化
     * @param callback(err)
     */
    init: function(callback) {
        this.config = clone(defaultGlobal);

        var cursor = DB.world.find();
        cursor.each(function(err, item){
            if (err) {
                callback(err); return;
            }

            if (item) {
                if (item._id == "usedRoomIds") {
                    this.usedRoomIds = item;
                } else if (item._id == "matchSN") {
                    this.matchSN = item;
                } else {
                    if (this.config.hasOwnProperty(item._id)) {
                        var v = clone(item);
                        delete v._id;
                        this.config[item._id] = v;
                    }
                }
            }

            if (cursor.isClosed()) {
                callback && callback();
            }
        }.bind(this));
    },

    /**
     *
     * @param id
     * @param callback(err)
     */
    save: function(id, callback) {
        var obj = this.config[id];
        if (!obj) {
            callback && callback(); return;
        }

        var item = clone(obj);
        item._id = id;
        DB.world.save(item, function(err) {
            callback && callback(err);
        });
    },

    saveAll: function(callback) {
        var self = this;
        async.series([
            function(cb) {
                DB.world.save(self.usedRoomIds, function(err) {
                    cb();
                });
            }.bind(this),
            function(cb) {
                DB.world.save(self.matchSN, function(err) {
                    cb();
                });
            }.bind(this)
        ], function(err) {
            callback && callback(err);
        });
    },

    /**
     * 申请一个房卡场房间号
     */
    allocCardRoomId: function() {
        var usedRoomIds = this.usedRoomIds.ids;

        var group = Date.getStamp()%90 + 10;
        var curId = usedRoomIds[group] || ExNumber.rand(9999);
        curId++;
        usedRoomIds[group] = curId;

        return group*10000 + curId;
    },

    /**
     * 申请一个金币场房间
     */
    allocCoinRoomId: function() {
        var usedRoomIds = this.usedRoomIds.ids;

        var group = 1;
        var curId = usedRoomIds[group] || Def.COIN_ROOM_ID_MIN;
        if (curId >= (Def.MATCH_ROOM_ID_MIN - 1)) {
            curId = Def.COIN_ROOM_ID_MIN;
        }

        curId++;

        usedRoomIds[group] = curId;

        return curId;
    },

    /**
     * 申请一个比赛场房间号
     * @param matchId 比赛场次编号
     */
    allocMatchRoomId: function(matchId) {

        var usedRoomIds = this.usedRoomIds.ids;

        var group = 2;
        var curId = usedRoomIds[group] || Def.MATCH_ROOM_ID_MIN;
        if (curId >= (Def.ROOM_ID_MAX - 1)) {
            curId = Def.MATCH_ROOM_ID_MIN;
        }

        curId++;

        usedRoomIds[group] = curId;

        return curId;
    },

    /**
     * 申请一个比赛场序号
     * @param matchId
     */
    allocMatchSN: function(matchId) {

        // 需要生成一个5位的流水号
        var matchSNValue = this.matchSN.value;

        var group = Date.getStamp() % 90 + 10;
        var curId = matchSNValue[group] || ExNumber.rand(9999);
        curId++;
        matchSNValue [group] = curId;

        return group * 1000 + curId;

        //// 获取当前的流水号是否是唯一的
        //Ext.generateRandomStr (5, 0);
        //this.matchSN.value++;
        //return this.matchSN.value;
    },

    getConfig: function(id, attr) {
        if (!id) {
            return this.config;
        }

        var mainValue = this.config[id];
        if (!mainValue) {
            return null;
        }

        return (attr) ? mainValue[attr] : mainValue;
    },

    setConfig: function(id, attr, value) {

        var args = arguments;

        var mainValue = this.config[id];
        if (!mainValue) {
            return;
        }

        // 鉴于有参数缺少的情况下需要进行特殊判断
        if (args.length == 2) {

            // 用于针对于某个独立配置直接赋值
            // 因此只有两个参数，所以attr不能为null
            if (attr == null) {
                return;
            }

            this.config[id] = attr;
        } else if (args.length == 3) {
            mainValue[attr] = value;
        } else {
            return;
        }

        this.save(id);
    }
};

exports.GlobalManager = GlobalManager;